package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Des;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.ShareDialog;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.qrcode.QRCodeActivity;
import com.zhongshengnetwork.rightbe.qrcode.tools.QRCodeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class WZTShareActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private ImageView qrcodeImageView;
    private TextView qrcode_title;
    private RelativeLayout qrcode_img_layout;
    private WeiShuInfoDetailModel weiShuInfoDetailModel;
    private boolean isShareWx = false;
    private String shareUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wztshare);
        weiShuInfoDetailModel = (WeiShuInfoDetailModel)getIntent().getSerializableExtra("model");
        qrcode_title = (TextView) findViewById(R.id.qrcode_title);
        qrcode_title.setText(weiShuInfoDetailModel.getTitle());
        qrcode_img_layout = (RelativeLayout) findViewById(R.id.qrcode_img_layout);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.setClickListener(this);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(WZTShareActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }

                PermissionUtils.isPictureNote(WZTShareActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            final List<String> menu = new ArrayList<String>();
                            menu.add("保存");
                            menu.add("分享");
                            ActionSheetDialog actionSheetDialog = new ActionSheetDialog(WZTShareActivity.this)
                                    .builder()
                                    .setTitle("")
                                    .setCancelable(false)
                                    .setCanceledOnTouchOutside(true);
                            for (String m : menu){
                                actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if (which == 1){
                                            final Bitmap bitmap = viewConversionBitmap(qrcode_img_layout);
                                            if (bitmap != null){
                                                CommonUtils.saveBmp2Gallery(bitmap,System.currentTimeMillis()+"");
                                            }
                                        }else if (which == 2){
                                            showShare();
                                        }
                                    }
                                });
                            }
                            actionSheetDialog.show();
                        }
                    }
                });

            }
        });

        qrcodeImageView = (ImageView) findViewById(R.id.activity_qrcode_qrimg);
        final String filePath = getFileRoot(WZTShareActivity.this) + File.separator
                + "qr_" + System.currentTimeMillis() + ".jpg";

        //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                String content = Constant.QRCodeHOST+"weishu/share.do?";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("weishuId",weiShuInfoDetailModel.getId()+"");
                String code = jsonObject.toString();
                try {
                    code = Des.encryptDES(code,Constant.DESKey);
                    content += code;
                }catch (Exception e){
                    return;
                }
                shareUrl = content;
                int W = dip2px(WZTShareActivity.this, ScreenUtils.getScreenWidth(WZTShareActivity.this));
                boolean success = QRCodeUtil.createQRImage(content, W, W,
                        null,
                        filePath);

                if (success) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            qrcodeImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                            //showShare();
                        }
                    });
                }
            }
        }).start();

        showShare();

    }

    private static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Log.e("TAG", "width: " + w + " height: " + h);
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        //v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void showShare(){

        if (CommonUtils.isEmpty(shareUrl)){
            String content = Constant.QRCodeHOST+"weishu/share.do?";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("weishuId",weiShuInfoDetailModel.getId()+"");
            String code = jsonObject.toString();
            try {
                code = Des.encryptDES(code,Constant.DESKey);
                content += code;
            }catch (Exception e){
                return;
            }
            shareUrl = content;
        }

        final ShareDialog shareDialog = new ShareDialog(WZTShareActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        shareDialog.friend_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到朋友圈
                isShareWx = false;
                new getImageCacheAsyncTask(WZTShareActivity.this).execute(weiShuInfoDetailModel.getCover());

            }
        });
        shareDialog.wx_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享给微信好友
                isShareWx = true;
                new getImageCacheAsyncTask(WZTShareActivity.this).execute(weiShuInfoDetailModel.getCover());

            }
        });
        shareDialog.wb_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                String shareUrl = Constant.QRCodeHOST+"weishu/share.do?";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("weishuId",weiShuInfoDetailModel.getId()+"");
                String code = jsonObject.toString();
                try {
                    code = Des.encryptDES(code,Constant.DESKey);
                    shareUrl += code;
                }catch (Exception e){
                    return;
                }
                //微博
                CustomApplication.WbShareType = 4;
                CustomApplication.WbShareSourceId = weiShuInfoDetailModel.getId()+"";
                CustomApplication.WbShareTitle = weiShuInfoDetailModel.getTitle();
                CustomApplication.WbShareText = weiShuInfoDetailModel.getDetail();
                CustomApplication.WbShareActionUrl = shareUrl;
                Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                //发送广播
                sendBroadcast(mIntent);
            }
        });
        shareDialog.qq_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到qq
                shareLinkToQQ(0,weiShuInfoDetailModel.getTitle(), weiShuInfoDetailModel.getDetail(), shareUrl);
            }
        });
        shareDialog.zone_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //qq空间
                shareLinkToQQ(1,weiShuInfoDetailModel.getTitle(), weiShuInfoDetailModel.getDetail(), shareUrl);
            }
        });
        shareDialog.show();
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    //分享链接到微信
    private void shareLinkToWX(int type,String url,String title,String content, Bitmap bmp){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        if (bmp == null){
            Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
            msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        }else {
            msg.thumbData = CommonUtils.bitmapToByteArray(bmp,true);
        }
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            //Log.e("TAG","分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    //分享到qq
    private Bundle params;
    private void shareLinkToQQ(int type,String title, String content, String url){
        params = new Bundle();
        if (type == 0){//QQ
            //分享链接到QQ
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址LangShareUrl+langInfoModel.getLangid()
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,weiShuInfoDetailModel.getCover());// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(WZTShareActivity.this, params, mIUiListener);
                }
            });
        }else {//QQ空间
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址LangShareUrl+langInfoModel.getLangid()
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,weiShuInfoDetailModel.getCover());// 网络图片地址
            params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(WZTShareActivity.this, params, mIUiListener);
                }
            });
        }
    }

    //下载分享图片
    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl =  params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Log.e("path", path);
            Bitmap bmp= BitmapFactory.decodeFile(path);
            bmp = CommonUtils.getZoomImage(bmp,24);//最大32k
            //0-朋友圈 1-微信
            if (isShareWx == false){
                shareLinkToWX(0,shareUrl,weiShuInfoDetailModel.getTitle(),weiShuInfoDetailModel.getDetail(),bmp);
            }else{
                shareLinkToWX(1,shareUrl,weiShuInfoDetailModel.getTitle(),weiShuInfoDetailModel.getDetail(),bmp);
            }
        }
    }

}

